package com.example.ormsqlsplicingframe1.orm.note;

import com.alibaba.druid.util.StringUtils;
import com.example.ormsqlsplicingframe1.orm.Util.ReflectionUtil;
import com.example.ormsqlsplicingframe1.orm.Util.SerializableFunction;
import com.example.ormsqlsplicingframe1.orm.wrapper.SelectWrapper;
import com.google.common.base.Joiner;
import lombok.extern.log4j.Log4j;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

public class Window<T> {
    private String partitionBy;
    private SelectWrapper selectWrapper;
    private String orderBy;

    public Window() {
    }

    private String funName;

    public Window(SelectWrapper selectWrapper, String funName) {
        this.funName = funName;
        this.selectWrapper = selectWrapper;
    }


    public Window<T> Partition(SerializableFunction<T, ?>... columns) {
        Set<String> col = Arrays.stream(columns).map(ReflectionUtil::getFieldName).collect(Collectors.toSet());
        partitionBy = Joiner.on(",").join(col);
        return this;
    }

    public Window<T> order(SerializableFunction<T, ?>... columns) {
        Set<String> col = Arrays.stream(columns).map(ReflectionUtil::getFieldName).collect(Collectors.toSet());
        orderBy = Joiner.on(",").join(col);
        return this;
    }

    public SelectWrapper<T> endWindow() {
        StringBuilder winsql = new StringBuilder();
        winsql.append(funName + " over " + " ( ");
        if (!StringUtils.isEmpty(partitionBy)) {
            winsql.append("partition by " + partitionBy);
        }
        if (!StringUtils.isEmpty(orderBy)) {
            winsql.append("order by " + orderBy);
        }
        winsql.append(" ) ");
        //selectWrapper.getWindows().add(winsql.toString());

        return selectWrapper;
    }
}
